package com.person.ntv.controller.sys;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
/*import ntv.office.excel.bean.DataSet;
import ntv.office.excel.bean.DataSetImport;
import ntv.office.excel.bean.ImportResult;
import ntv.office.excel.exception.AtrrToCellException;
import ntv.office.excel.exception.LoadTemplateException;
import ntv.office.excel.util.ExcelUtil;*/
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.Page;
import com.person.Constants;
import com.person.common.PageParams;
import com.person.easyui.EasyUItools;
import com.person.easyui.TreeNodeRule;
import com.person.exception.ServiceException;
import com.person.ntv.entity.sys.SysCode;
import com.person.ntv.entity.sys.SysDept;
import com.person.ntv.entity.sys.SysOrg;
import com.person.ntv.entity.sys.SysRole;
import com.person.ntv.entity.sys.SysUser;
import com.person.ntv.service.sys.CommonService;
import com.person.ntv.service.sys.SysDeptService;
import com.person.ntv.service.sys.SysOrgService;
import com.person.ntv.service.sys.SysRoleService;
import com.person.ntv.service.sys.SysUserService;
import com.person.ntv.shiro.util.PasswordHelper;

@Controller
@RequestMapping("/system/sysUser")
public class SysUserController {
	@Autowired
		private SysUserService  sysUserService ;
	@Autowired
		private CommonService commonService;
	@Autowired
		private SysDeptService sysDeptService;
	@Autowired
		private SysOrgService sysOrgService;
	@Autowired
		private SysRoleService sysRoleService;
	@Autowired
	    private PasswordHelper passwordHelper;
		
		@RequestMapping("/listPage")
		public String  getUserPage(ModelMap mv)throws Exception{
			initCode(mv);
			List<SysCode> codeList = commonService.getCodeList("SysUserStatus",true);
			mv.addAttribute("SysUserStatus",JSONArray.fromObject(codeList).toString());
			return "/system/user/userList";
		}
		
		@RequestMapping("/userList")
		@ResponseBody
		public Map<String,Object> getUserList(PageParams myPage) throws Exception{
			Map<String,Object> map=new HashMap<String,Object>();
			Page<Map<String,Object>> page=sysUserService.getUserPage(myPage);
	        map.put("total",page.getTotal());
	        map.put("rows",page.getResult());
			return map;
		}
		
		@RequestMapping("/addPage")
		public String  addUserPage(ModelMap mv) throws Exception{
			initCode(mv);
			return "/system/user/userAdd";
		}
		
		@RequestMapping("/editPage")
		public String  editUserPage(String id,ModelMap mv) throws Exception{
			try {
			initCode(mv);
		    SysUser user =sysUserService.selectByPrimaryKey(new BigDecimal(id));
		    List<Map<String,Object>> roleList=sysUserService.getUserRoleList(Integer.valueOf(String.valueOf(user.getId())));
		    StringBuffer sb=new StringBuffer("");
		    if(roleList!=null)
		    	for(Map<String,Object>map:roleList){
		    		sb.append(map.get("roleId")+",");
		    	}
		    user.setRoleList(sb.length()>1?sb.toString().substring(0,sb.length()-1):sb.toString());
		    mv.addAttribute("user",user);
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"查询出错！");
			}
			return "/system/user/userEdit";
		}
		
		@RequestMapping("/addUser")
		public String  addUser(ModelMap mv,SysUser sysUser,HttpServletRequest req) throws Exception{
			try {
				String pwd=req.getParameter("userPassword");
				String pwd2=req.getParameter("userPassword2");
				if(!String.valueOf(pwd).equals(pwd2))
					throw new ServiceException("两次输入密码不一致！");
				 passwordHelper.encryptPassword(sysUser);
				sysUserService.addUser(sysUser);
				mv.addAttribute("error", "0");
				mv.addAttribute("msg","保存成功！");
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"保存失败！");
			}
			return "/system/user/userAdd";
		}
		
		@RequestMapping("/editUser")
		public String  editUser(ModelMap mv,SysUser sysUser) throws Exception{
			try {
				sysUserService.updateUser(sysUser); 
				mv.addAttribute("error", "0");
				mv.addAttribute("msg","保存成功！");
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"保存失败！");
			}
			return "/system/user/userEdit";
		}
		
		@RequestMapping("/delUser")
		@ResponseBody
		public Map<String,Object>  delUser(Integer[]ids,HttpServletRequest request) throws Exception{
			Map<String,Object> map=new HashMap<String,Object>();
			try {
				sysUserService.deleteByPrimaryKeys(ids);
				map.put("error", "0");
				map.put("msg","删除成功！");
			} catch (ServiceException e) {
				map.put("error", "1");
				map.put("msg",e.getMessage()+"删除失败！");
			}
			return map;
		}
		
		@RequestMapping("/detailPage")
		public String  detailUserSetPage(String id,ModelMap mv) throws Exception{
			try {
		    SysUser user = sysUserService.selectByPrimaryKey(new BigDecimal(id));
		    SysDept dept= sysDeptService.selectByPrimaryKey(user.getDeptId());
		    List<Map<String,Object>> roleList=sysUserService.getUserRoleList(Integer.valueOf(String.valueOf(user.getId())));
		    StringBuffer sb=new StringBuffer("");
		    if(roleList!=null)
		    for(Map<String,Object>map:roleList){
		    	sb.append(String.valueOf(map.get("roleName"))+",");
		    }
		    user.setRoleList(sb.length()>1?sb.toString().substring(0,sb.length()-1):sb.toString());
		    mv.addAttribute("user",user);
		    mv.addAttribute("dept",dept);
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"查询出错！");
			}
			return "/system/user/userDetail";
		}
		
		@RequestMapping("/validateUserName")
		@ResponseBody
		public boolean validateUserName(SysUser sysUser) throws Exception{
			try {
				if(sysUser.getUserName()==null)sysUser.setUserName("");
				int cnt=commonService.validateOne("sys_user","user_name",sysUser.getUserName(), sysUser.getId()==null?null:String.valueOf(sysUser.getId()));
				if(cnt==0)
				return true;
			} catch (ServiceException e) {
	           e.printStackTrace();
			}
			return false;
		}
		
		@RequestMapping("/validateUserAccount")
		@ResponseBody
		public boolean validateUserAccount(SysUser  sysUser) throws Exception{
			try {
				if(sysUser.getUserAccount()==null)sysUser.setUserAccount("");
				int cnt=commonService.validateOne("sys_user","user_account",sysUser.getUserAccount(), sysUser.getId()==null?null:String.valueOf(sysUser.getId())); 
				if(cnt==0)
				return true;
			} catch (ServiceException e) {
				e.printStackTrace();
			}
			return false;
		}
		
		private void initCode(ModelMap mv){
			//部门
			List<SysDept> deptList= sysDeptService.selectAll();
			SysDept dept=new SysDept();
			dept.setDeptAbbr("请选择");
			deptList.add(0,dept);
			mv.addAttribute("SysDept",JSONArray.fromObject(EasyUItools.getUItreeList(EasyUItools.getTreeNodeList(deptList,new TreeNodeRule("id", "upDeptId","deptAbbr",null,null,null)))).toString());
			//组织机构
			List<SysOrg> orgList= sysOrgService.selectAll();
			SysOrg org=new SysOrg();
			org.setOrgAbbr("请选择");
			orgList.add(0,org);
			mv.addAttribute("SysOrg",JSONArray.fromObject(EasyUItools.getUItreeList(EasyUItools.getTreeNodeList(orgList,new TreeNodeRule("id", "upOrgId","orgAbbr",null,null,null)))).toString());
			mv.addAttribute("SysUserStatus",JSONArray.fromObject(commonService.getCodeList("SysUserStatus",true)).toString());
			//角色
			List<SysRole>roleList=sysRoleService.selectAll();
			mv.addAttribute("RoleList",JSONArray.fromObject(roleList).toString());
		}
		
		@RequestMapping("/resetPwdPage")
		public String  resetPwdPage(ModelMap mv,HttpServletRequest request) throws Exception{
			mv.addAttribute("id", request.getParameter("id"));
			return "/system/user/userResetPwd";
		} 
		
		@RequestMapping("/resetPwd")
		public String  resetPwd(ModelMap mv,SysUser sysUser,HttpServletRequest request) throws Exception{
			try {
				String pwd2=request.getParameter("userPassword2");
				if(StringUtils.isNotBlank(pwd2)&&pwd2.equals(sysUser.getUserPassword())){
				sysUser=	sysUserService.selectByPrimaryKey(sysUser.getId());
				sysUser.setUserPassword(pwd2);
				passwordHelper.encryptPassword(sysUser);
				sysUserService.updateByPrimaryKeySelective(sysUser);
				mv.addAttribute("error", "0");
				mv.addAttribute("msg","保存成功！");
				}else{
					mv.addAttribute("error", "1");
					mv.addAttribute("msg","两次输入的密码不一致！");
				}
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"保存失败！");
			}
			return "/system/user/userResetPwd";
		}
		
		@RequestMapping("/editPwdPage")
		public String  editPwdPage(ModelMap mv,HttpServletRequest request) throws Exception{
			SysUser curUser=(SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
			mv.addAttribute("user", curUser);
			return "/system/user/userEditPwd";
		} 
		
		@RequestMapping("/editPwd")
		public String  editPwd(ModelMap mv,SysUser sysUser,HttpServletRequest request) throws Exception{
			try {
				String pwd0=request.getParameter("userPassword0");
				String pwd=request.getParameter("userPassword");
				String pwd2=request.getParameter("userPassword2");
				SysUser curUser=(SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
				sysUser=sysUserService.selectByPrimaryKey(curUser.getId());
				String oldPwd=sysUser.getUserPassword();
				sysUser.setUserPassword(pwd0);
				if(oldPwd.equals(passwordHelper.getEncryptPassword(sysUser))){
				if(StringUtils.isNotBlank(pwd2)&&pwd2.equals(pwd)){
				sysUser.setUserPassword(pwd2);
				passwordHelper.encryptPassword(sysUser);
				sysUserService.updateByPrimaryKeySelective(sysUser);
				mv.addAttribute("error", "0");
				mv.addAttribute("msg","保存成功！");
				}else{
					mv.addAttribute("error", "1");
					mv.addAttribute("msg","两次输入的密码不一致！");
				}
				}else{
					mv.addAttribute("error", "1");
					mv.addAttribute("msg","密码错误！");
				}
			} catch (ServiceException e) {
				mv.addAttribute("error", "1");
				mv.addAttribute("msg",e.getMessage()+"保存失败！");
			}
			if(mv.get("error").toString().equals("1"))
			return "/system/user/userEditPwd";
			return "redirect:/sysLogin/logout";
		}
		
		/*@RequestMapping("/export")
		public void export(HttpServletRequest request,HttpServletResponse response,PageParams myPage){
			myPage.setPage(0);
			myPage.setRows(100000);
			Page<Map<String,Object>> page=sysUserService.getUserPage(myPage);
			List<Map<String,Object>> list=page.getResult();
			String name="用户信息.xlsx";
			response.setContentType("application/msword;charset=utf-8");
			try {
				response.setHeader("Content-Disposition", "attachment; filename="
						+ new String(name.getBytes("GB2312"),"8859_1"));
				OutputStream out=response.getOutputStream();
				DataSet data=new DataSet(0,list	);
				List<DataSet>dataSets=new ArrayList<DataSet>();
				dataSets.add(data);
				String xmlPath=request.getSession().getServletContext().getRealPath("/")+"WEB-INF/jsp/system/template/xml/sysUser.xml";
				String xlsPath=request.getSession().getServletContext().getRealPath("/")+"WEB-INF/jsp/system/template/sysUser.xlsx";
				ExcelUtil.getInstance().expXls(xmlPath,xlsPath, dataSets, out);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (LoadTemplateException e) {
				e.printStackTrace();
			} catch (AtrrToCellException e) {
				e.printStackTrace();
			}
		}*/
		
		@RequestMapping("importPage")
		public String importPage(ModelMap mv)throws Exception{
			mv.addAttribute("importUrl","sysUser/import");
			return "/common/import/importCommon";
		}
		
	/*	@RequestMapping("import")
		public String importData(HttpServletRequest request,HttpServletResponse response,ModelMap mv)throws Exception{
			try {
				List<Object>userList=new ArrayList<Object>();
				DataSetImport data=new DataSetImport(0,userList,Map.class);
				List<DataSetImport>dataSets=new ArrayList<DataSetImport>();
				dataSets.add(data);
				String xmlPath=request.getSession().getServletContext().getRealPath("/")+"WEB-INF/jsp/system/template/xml/sysUser.xml";
				InputStream input=null;
				//创建一个通用的多部分解析器  
		        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		        //判断 request 是否有文件上传,即多部分请求  
		        if(multipartResolver.isMultipart(request)){  
		            //转换成多部分request
		            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
		            //取得request中的所有文件名  
		            Iterator<String> iter = multiRequest.getFileNames();
		            //String uuid=request.getParameter("foreignUuid");
		            while(iter.hasNext()){  
		               //记录上传过程起始时的时间，用来计算上传时间  
		               //取得上传文件  
		                MultipartFile file = multiRequest.getFile(iter.next());
		                if(file != null&&file.getSize()>0){
		                	input=file.getInputStream();
		                	break;
		                }
		            }
		        }
		        ImportResult result = ExcelUtil.getInstance().importXls(xmlPath, dataSets, input);
		        if(!result.isImportSuccess()){
		        String name="用户信息_上传错误信息.xlsx";
				response.setContentType("application/msword;charset=utf-8");
				response.setHeader("Content-Disposition", "attachment; filename="
						+ new String(name.getBytes("GB2312"),"8859_1"));
				OutputStream out=response.getOutputStream();
				Workbook wb=result.getWb();
		        wb.write(out);
		        wb.close();
		        out.close();
		    }
		        mv.addAttribute("error", "0");
				mv.addAttribute("msg","导入成功！");
			}catch(Exception e){
				mv.addAttribute("error", "1");
				mv.addAttribute("msg","导入失败！");
			}
			return "/common/import/importCommon";
		}*/
		
		@RequestMapping("exportTemplate")
		public void  exportTemplate(HttpServletRequest request, HttpServletResponse response){
			 String name="用户信息导入模板.xlsx";
				response.setContentType("application/msword;charset=utf-8");
				try {
					response.setHeader("Content-Disposition", "attachment; filename="
							+ new String(name.getBytes("GB2312"),"8859_1"));
					OutputStream out=response.getOutputStream();
					String filePath=request.getSession().getServletContext().getRealPath("/")+"WEB-INF/jsp/system/template/sysUser.xlsx";
					File file=new File(filePath);
					InputStream in=new FileInputStream(file);
					byte []bytes=new byte[10240];
					int len=0;
					while((len=in.read(bytes))!=-1){
						out.write(bytes,0,len);
					}
					out.flush();
					in.close();
					out.close();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
}
